package com.usian.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.common.fastDFS.FastDFSClient;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmMaterialDto;
import com.usian.model.media.pojos.WmMaterial;
import com.usian.model.media.pojos.WmNewsMaterial;
import com.usian.model.media.pojos.WmUser;
import com.usian.utils.threadlocal.WmThreadLocalUtils;
import com.usian.wemedia.mapper.WmMaterialMapper;
import com.usian.wemedia.mapper.WmNewsMaterialMapper;
import com.usian.wemedia.service.WmMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;

@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FastDFSClient fastDFSClient;

    @Value("${fileServerUrl}")
    private String  host;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Override
    public ResponseResult uploadPicture(MultipartFile file) {

        try {
            /*校验文件*/
            if (file == null){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }

            /*上传成功*/
              String fullPath  = fastDFSClient.uploadFile(file);

            //3.保存素材数据到表中 wm_material

            WmMaterial wmMaterial = new WmMaterial();
            wmMaterial.setUrl(fullPath);
            wmMaterial.setIsCollection((short)0);

            WmUser user = WmThreadLocalUtils.getUser();
            if (user!=null){
                wmMaterial.setUserId(user.getId());
            }

            wmMaterial.setType((short)0);
            wmMaterial.setCreatedTime(new Date());
            this.save(wmMaterial);
            /*保存完对象  之所以重新赋值 但不同步到数据库  是因为这个只是提供前端能展示图片*/
            wmMaterial.setUrl(host+fullPath);

            return ResponseResult.okResult(wmMaterial);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public ResponseResult findList(WmMaterialDto dto) {

        if (dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();

        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        WmUser user = WmThreadLocalUtils.getUser();
        if (user!=null){
            lambdaQueryWrapper.eq(WmMaterial::getUserId,user.getId());
        }
        if (dto.getIsCollection()!=null && dto.getIsCollection()==1){
            lambdaQueryWrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }

        lambdaQueryWrapper.orderByDesc(WmMaterial::getCreatedTime);

        Page pageParam = new Page(dto.getPage(),dto.getSize());

        IPage result = page(pageParam,lambdaQueryWrapper);

        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) result.getTotal());

        List<WmMaterial> list = result.getRecords();

        for (WmMaterial wmMaterial : list) {
            wmMaterial.setUrl(host+wmMaterial.getUrl());
        }

        pageResponseResult.setData(list);


        return pageResponseResult;
    }

    @Override
    public ResponseResult delPicture(Integer id) {

        if (id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        WmMaterial wmMaterial = this.getById(id);

        if (wmMaterial == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        QueryWrapper<WmNewsMaterial> queryWrapper = new QueryWrapper<>();

        queryWrapper.lambda().eq(WmNewsMaterial::getMaterialId,id);

        Integer count = wmNewsMaterialMapper.selectCount(queryWrapper);

        /*如果关系表里面能查到 就说明改图片被引用 所以不能删除*/
        if (count>0){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }

        /*删除fastDFS的图片*/
        fastDFSClient.delFile(wmMaterial.getUrl());

        /*删除素材表*/
        this.removeById(id);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        update(Wrappers.<WmMaterial>lambdaUpdate().set(WmMaterial::getIsCollection,type)
                .eq(WmMaterial::getId,id));



        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

}
